<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible" width="60%">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="80px">
      <el-form-item label="所属分类" prop="cateId">
        <el-input placeholder="请选择分类" :value="current.name" type="text" readonly>
          <template slot="suffix">
            <el-button class="el-icon-edit" @click="checkSort" type="text"> 选择分类</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="题干内容" prop="info">
        <ck-editor ref="ckEditor" :change="contentChanged"/>
      </el-form-item>
      <el-form-item label="关键词" prop="value">
<!--        <el-tag v-for="x in phraseList" :key="x" closable>{{x}}</el-tag>-->
        <el-tag
          class="answer-item"
          v-for="(text, index) in phraseList"
          :key="index"
          closable
          @close="removeBlankText(index)"
        >{{text}}
        </el-tag>
        <el-input v-model="dataForm.value"></el-input>
        <el-button @click="btnImportant()">添加关键词</el-button>
      </el-form-item>
      <el-form-item label="参考答案" prop="answ">
        <el-input type="textarea" v-model="dataForm.answ" placeholder="参考答案"/>
      </el-form-item>
      <!-- 试题难度 -->
      <el-form-item label="试题难度" prop="level">
        <el-radio-group v-model="dataForm.level">
          <el-radio :label="0">简单</el-radio>
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="2">困难</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="答案解析" prop="analysis">
        <el-input type="textarea" v-model="dataForm.analysis" placeholder="答案解析"/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" :loading="loading">确定</el-button>
    </div>
    <!-- 分类管理 -->
    <el-dialog title="分类管理" :visible.sync="dialogFormVisible" :show-close="false"
               append-to-body width="30%">
      <paper-cate ref="paperCate" v-if="paperCate" :setCurrent="setCurrent" :current="current"
                  :url="{
                                update:'/exam-admin/ques/cate/update',
                                save:'/exam-admin/ques/cate/save',
                                delete:'/exam-admin/ques/cate/delete',
                                tree:'/exam-admin/ques/cate/tree'
                                }"/>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
  import paperCate from './../../../views/modules/paper/papercate'
  import CkEditor from '../../../components/ckEditor/ckEditor'

  export default {
    data () {
      let checkOptions = (rule, value, callback) => {
        value.forEach(x => {
          if (!x.option) {
            return callback(new Error(`${x.key}选项不能为空`))
          }
        })
        callback()
      }
      return {
        dialogFormVisible: false,
        current: {},
        paperCate: false,
        visible: false,
        loading: false,
        phraseList: [],
        dataForm: {
          id: 0,
          cateId: '',
          info: '',
          value: '',
          answ: '',
          questype: 5,
          normalWords: '',
          level: 0,
          analysis: ''
        },
        dataRule: {
          cateId: [{required: true, message: '分类不能为空', trigger: 'blur'}],
          choiceqstOps: [{validator: checkOptions, trigger: 'blur'}],
          info: [{required: true, message: '题干内容不能为空', trigger: 'blur'}],
          answ: [{required: true, message: '答案不能为空', trigger: 'blur'}],
          level: [{required: true, message: '试题难度（0-简单，1-普通，2-困难）不能为空', trigger: 'blur'}]
        }
      }
    },
    components: {
      CkEditor,
      paperCate
    },
    methods: {
      contentChanged (content) {
        this.dataForm.info = content
      },
      setCurrent (data) {
        if (data.id) {
          this.current = data
          this.dataForm.cateId = data.id
          this.$nextTick(_ => this.$refs['dataForm'].validateField('cateId'))
        }
      },
      btnImportant() {
        if(this.dataForm.value == '') {
          this.$notify.error({ title: '失败', message: '请填写关键词' })
          return false
        }
        this.phraseList.push(this.dataForm.value)
        this.dataForm.value = ''
      },
      checkSort () {
        this.dialogFormVisible = true
        this.paperCate = true
        this.$nextTick(() => {
          this.$refs.paperCate.init()
        })
      },
      removeBlankText(index) {
        this.phraseList.splice(index, 1)
      },
      init (id, quesCateId) {
        this.current = {
          name: '',
          id: ''
        }
        this.dataForm.cateId = quesCateId
        this.dataForm.id = id || 0
        this.phraseList = []
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/exam-admin/ques/qa/info/${this.dataForm.id}`),
              method: 'post'
            }).then(data => {
              if (data && data.code === 200) {
                this.dataForm.choiceqstOps = []
                this.setCurrent({name: data.data.cateName, id: data.data.cateId})
                this.$refs.ckEditor.setData(data.data.info)
                // let options = JSON.parse(data.data.options)
                // if (options && options.length > 0) {
                //   for (let i = 0; i < options.length; i++) {
                //     this.dataForm.choiceqstOps.push({
                //       key: options[i].key,
                //       option: options[i].option
                //     })
                //   }
                // }
                this.dataForm.answ = data.data.answ
                this.phraseList = data.data.normalWords ? JSON.parse(data.data.normalWords) : []
                this.dataForm.info = data.data.info
                this.dataForm.level = data.data.level
                this.dataForm.analysis = data.data.analysis
              }
            })
          } else {
            this.$refs.ckEditor.setData('')
            this.dataForm.choiceqstOps = [
              {
                key: 'A',
                option: ''
              },
              {
                key: 'B',
                option: ''
              }
            ]
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            this.$http({
              url: this.$http.adornUrl(`/exam-admin/ques/qa/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: {
                'id': this.dataForm.id || undefined,
                'cateId': this.dataForm.cateId,
                'info': this.dataForm.info,
                'normalWords': this.phraseList.length ? JSON.stringify(this.phraseList) : '',
                'level': this.dataForm.level,
                'analysis': this.dataForm.analysis,
                'answ': this.dataForm.answ,
                'quesType': this.dataForm.questype
              }
            }).then(data => {
              if (data && data.code === 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500
                })
                this.visible = false
                this.$emit('refreshDataList')
              } else {
                this.$message.error(data.msg)
              }
              this.loading = false
            })
          }
        })
      },
      addOption () {
        if (this.dataForm.choiceqstOps.length >= 26) {
          return false
        }
        this.dataForm.choiceqstOps.push(
          {
            key: this.words[this.dataForm.choiceqstOps.length],
            option: ''
          }
        )
      },
      // 移除一个选项
      removeOption (index) {
        this.dataForm.choiceqstOps.splice(index, 1)
        for (let i = 0; i < this.dataForm.choiceqstOps.length; i++) {
          this.dataForm.choiceqstOps[i].key = this.words[i]
        }
        this.$nextTick(_ => this.$refs['dataForm'].validateField('choiceqstOps'))
      }
    }
  }
</script>
